import { createStore } from 'vuex'
import { reactive } from 'vue'

const store = createStore({
  state: {
    connections: reactive([]),
    globalMsg: '',
    userInfo: {
      id: null,
      name: ''
    }
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setConnections(state, connections) {
      state.connections = connections
    },
    appendConnection(state, connection) {
      state.connections.push({
        ...connection
      })
    },
    updateConnection(state, connection) {
      let idx
      state.connections.forEach((con, index) => {
        if (con.id !== connection.id) {
          return
        }
        idx = index
      })
      if (!idx) {
        return
      }
      Object.assign(state.connections[idx], connection)
    },
    removeConnection(state, connection) {
      let idx
      state.connections.forEach((con, index) => {
        if (con.id !== connection.id) {
          return
        }
        idx = index
      })
      state.connections.splice(idx, 1)
    },
    updateDatabaseList(state, { list, label }) {
      for (const connection of state.connections) {
        if (connection.label === label) {
          connection.databases = list
          break
        }
      }
    },
    updateGlobalMsg(state, msg) {
      state.globalMsg = msg
    }
  },
  getters: {
    openedConnections(state) {
      return state.connections.filter((connection) => connection.opened)
    },
    allConnections(state) {
      return state.connections
    },
    activeInfo(state) {
      const activeInfo = {
        connection: null,
        database: null
      }
      state.connections.forEach((connection) => {
        if (connection.active) {
          activeInfo.connection = connection
          activeInfo.database = null
          return false
        }
        if (connection.databases) {
          for (const database of connection.databases) {
            if (database.active) {
              activeInfo.connection = connection
              activeInfo.database = database
              return false
            }
          }
        }
      })
      return activeInfo
    }
  }
})

export default store
